package com.jiamao.goplay.ui.user;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.activity.OnBackPressedDispatcher;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import me.goldze.mvvmhabit.utils.KLog;

import com.google.android.material.appbar.AppBarLayout;
import com.gyf.immersionbar.ImmersionBar;
import com.jiamao.goplay.BR;
import com.jiamao.goplay.R;
import com.jiamao.goplay.adapter.UserWanToGoAdapter;
import com.jiamao.goplay.app.AppApplication;
import com.jiamao.goplay.app.AppViewModelFactory;
import com.jiamao.goplay.base.BaseMVVMFragment;
import com.jiamao.goplay.databinding.UserOthersUserInfoBinding;
import com.jiamao.goplay.ui.user.vm.AnonymousReportVM;
import com.jiamao.goplay.ui.user.vm.UserOtherInfoVM;
import com.jiamao.goplay.view.EmptyCallback;
import com.jiamao.goplay.view.HorizontalItemDecoration;
import com.jiamao.goplay.view.LoadingCallback;
import com.jiamao.goplay.view.TimeoutCallback;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.callback.SuccessCallback;
import com.kingja.loadsir.core.Convertor;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.util.DialogSettings;
import com.kongzue.dialog.v3.MessageDialog;
import com.netease.nim.uikit.api.NimUIKit;


/**
 * 他人资料页面
 */
public class OthersUserInfoFragment extends BaseMVVMFragment<UserOthersUserInfoBinding, UserOtherInfoVM> {
    private int mScrollY = 0;
    private Toolbar toolbar;
    private TextView title;
    private ImageView btnBack,btnMore;
    private LoadService loadService;
    private String uid;
@Override
        public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.user_others_user_info;
        }

@Override
public int initVariableId() {
        return BR.viewModel;
        }

@Override
public UserOtherInfoVM initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(UserOtherInfoVM.class);
        }

    @Override
    public void initViewObservable() {
        super.initViewObservable();

        CoordinatorLayout imageView = binding.curr;
        loadService = LoadSir.getDefault().register(imageView, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                Log.d("HTML","ASDASDASDASDDSD");
                  viewModel.getLoadInitData(uid);
                // 重新加载逻辑
            }
        },new Convertor<Integer>() {
            @Override
            public Class<? extends Callback> map(Integer httpResult) {
                Class<? extends Callback> resultCode = SuccessCallback.class;


                switch (httpResult) {
                    case 0://成功回调
                        resultCode = SuccessCallback.class;
                        break;
                    case 1://成功回调
                        resultCode = LoadingCallback.class;
                        break;
                    case 2://成功回调
                        resultCode = TimeoutCallback.class;
                        break;
                    case 3://成功回调
                        resultCode = EmptyCallback.class;
                        break;
                }
                KLog.d("HTML","httpResult "+httpResult+" resultCode"+resultCode);
                return resultCode;
            }
        });


        viewModel.uc.uiInitRefreshEvent.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer aBoolean) {
                //pSwitchObservable是boolean类型的观察者,所以可以直接使用它的值改变密码开关的图标
                loadService.showWithConvertor(aBoolean);
            }
        });

        viewModel.uc.startChat.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String aBoolean) {

                NimUIKit.startP2PSession(getActivity(),aBoolean);
            }
        });

        viewModel.uc.pSwitchEvent.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String aBoolean) {
                //pSwitchObservable是boolean类型的观察者,所以可以直接使用它的值改变密码开关的图标
                title.setText(aBoolean);
            }
        });
        viewModel.uc.refMaxNum.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer aBoolean) {
                //pSwitchObservable是boolean类型的观察者,所以可以直接使用它的值改变密码开关的图标121212
                KLog.d("html "+aBoolean);
//                    binding.pageIndicatorView.set
                    binding.pageIndicatorView.setCount(aBoolean);
                    binding.pageIndicatorView.setSelection(0);
//                    binding.pageIndicatorV
                binding.userPhotoListView.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {/*empty*/}

                    @Override
                    public void onPageSelected(int position) {
                        binding.pageIndicatorView.setSelection(position);
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {/*empty*/}
                });
            }
        });

}

    @Override
public void initData() {
    super.initData();

    btnBack = binding.ivBack;
    btnMore = binding.ivMenu;
    title = binding.tvTitle;
    title.setText("");
    toolbar = binding.getRoot().findViewById(R.id.toolbar);
    //    binding.setAdapter(new UserWanToGoAdapter(getContext()));
    ImmersionBar.with(this). keyboardEnable(false).statusBarDarkFont(true).titleBar(toolbar).init();
    AppBarLayout appBarLayout = (AppBarLayout)  binding.getRoot().findViewById(R.id.app_bar);
        RecyclerView recyclerViewGotoList = binding.getRoot().findViewById(R.id.user_goto_listview);
        //  RecyclerView recyclerPhotoList = binding.getRoot().findViewById(R.id.user_photo_listview);

        recyclerViewGotoList.addItemDecoration(new HorizontalItemDecoration(11,getContext()));//10表示10dp
    appBarLayout.addOnOffsetChangedListener((appBarLayout1, verticalOffset) -> {


     //   recyclerPhotoList.addItemDecoration(new HorizontalItemDecoration(9,getContext()));//10表示10dp
        if (verticalOffset < 0 ){
            //   swipeRefreshLayout.setEnableRefresh(false);
        }else {
            //  swipeRefreshLayout.setEnableRefresh(true);
        }

        float offset = Math.abs(verticalOffset * 1.0f) / appBarLayout.getTotalScrollRange();

        Log.d("HTML","offset:"+offset);
        if (offset > 0.7){
            title.setVisibility(View.VISIBLE);
            btnBack.setImageResource(R.mipmap.icon_back);

            btnMore.setImageResource(R.mipmap.icon_more_blakcn);
        }else {
            title.setVisibility(View.INVISIBLE);
            btnBack.setImageResource(R.mipmap.icon_back_other_white);
            btnMore.setImageResource(R.mipmap.ic_more_white);
        }
        btnMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle bd =  new Bundle();
                bd.putString("uid",uid);
                startContainerActivity(AnonymousReportFragment.class.getCanonicalName(),bd);
            }
        });
        toolbar.setBackgroundColor(changeAlpha(getResources().getColor(R.color.orange)
              , offset));

    });

    if (getArguments()!=null){
        uid = getArguments().getString("uid");
    }


    viewModel.getLoadInitData(uid);

}


    /**
     * 根据百分比改变颜色透明度
     */
    public int changeAlpha(int color, float fraction) {


        int alpha = (int) (Color.alpha(color) * fraction);
        return Color.argb(alpha, 255, 255, 255);
    }


    void showLogoutDialog(){

        MessageDialog.build((AppCompatActivity) getContext())
                .setStyle(DialogSettings.STYLE.STYLE_IOS)
                .setTitle("资料还未保存")
                .setMessage("是否保存")
                .setOkButton("保存", new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {

                        //AppApplication.getInstance().startLogins();
                        return false;
                    }

                }).setCancelButton("不保存")
                .show();

    }


}